<template>
    <el-upload ref="uploadRef" class="upload-demo" action="http://ergou666.shop:8000/img/edit_favorite/"
        :auto-upload="false" :limit="1" :data="updateCoverData" :on-success="onSuccess" :headers="{ 'token': token }">
        <template #trigger>
            <div>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                    点击上传图片
                </div>
            </div>
        </template>
        
    </el-upload>
</template>
<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref, reactive, getCurrentInstance } from 'vue'
import type { UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { myToken } from "@/tools/api/api";
// 组件初始化
const instance = getCurrentInstance();
// 获取token
const token = ref(myToken())
// 修改封面数据
const updateCoverData = reactive({
    name: '',
    favorite: ''
})
instance?.proxy?.$Bus.on("favorData", (value: any) => {
    updateCoverData.name = value.name;
    updateCoverData.favorite = value.id;
    submitUpload();
})

/**
 * 文件上传成功时的钩子	
 */
const onSuccess = (res: any) => {
    console.log('res', res)
    if (res.code === 100) {
        ElMessage.success("上传成功")
        // 通知父组件重新渲染界面
        instance?.proxy?.$Bus.emit("reloadFavorite")
    } else ElMessage.error(res.msg)
}

// 上传文件数据
const uploadRef = ref<UploadInstance>()

//确认上传
const submitUpload = () => {
    console.log('1', 1)
    uploadRef.value!.submit()
}
</script>

<style lang="scss" scoped>
$item-height: 0.36rem;
$item-width: 0.6rem;
$a-font-size: 0.08rem;

.upload-demo {
    .el-icon--upload {
        font-size: $a-font-size*4;
    }

    .el-upload__text {
        font-size: $a-font-size;
        font-weight: bolder;
    }
}
</style>